//
// Highlight technique based on "highlight: JavaScript text higlighting jQuery plugin" (http://johannburkard.de), MIT Licensed.
//
highlight = function(keywords) {

   function highlightTextNode(node, word, pos)
   {
      var spannode = document.createElement('span');
      spannode.className = 'highlight';
      var middlebit = node.splitText(pos);
      var endbit = middlebit.splitText(word.length);
      var middleclone = middlebit.cloneNode(true);
      spannode.appendChild(middleclone);
      middlebit.parentNode.replaceChild(spannode, middlebit);   
   }

   function innerHighlight(node, keywords) 
   {
      var skip = 0;
      if (node.nodeType == 3) {

       for (var k = 0; k < keywords.length; k++) {
         word = keywords[k].toUpperCase();
         var pos = node.data.toUpperCase().indexOf(word);
         if (pos >= 0) {
          highlightTextNode(node, word, pos);
          skip = 1;
         }
       }
       
      } else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
        for (var i = 0; i < node.childNodes.length; ++i) {
          i += innerHighlight(node.childNodes[i], keywords);
        }
      }

      return skip;
   }

   innerHighlight(document.body, keywords);

};

	function clearHighlight()
	{
		// Terrible hack. Suggestions?
		var h,i=0,maxH=500;
		while(h = document.querySelector(".highlight") && i < maxH)
		{
			document.querySelector(".highlight").outerHTML=document.querySelector(".highlight").innerHTML;
			i++;
		}
	}

//
// Fetch keywords from the background page, originally set in the options page of this extension
//
onKeywordsRecieved = function(response) {
  var khwordsRaw = response.khwords;
  if (khwordsRaw) {
    var khwords = khwordsRaw.split(",");
    highlight(khwords);
  }
}


highlightHeartbeat = function() {
	chrome.extension.sendRequest({fetch: "khwords"}, onKeywordsRecieved);
}

highlightHeartbeat();
setTimeout("highlightHeartbeat()", 3000);

chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
	if(request.msg && request.msg=="callbg")
	{
		try {clearHighlight()} catch(e) {}
		highlightHeartbeat();
	}
  }
);







